import logging
from fastapi import APIRouter, Body, Depends, Query

from app.core.i18n import t
from app.core.deps import CurrentUser
from app.schemas.common import OrderSchema, PaginationParams, PaginationResult
from app.schemas.response import Response
from app.schemas.user import (
    UserCreateRequest,
    UserCreateResponse,
    UserDeleteResponse,
    UserDetailResponse,
    UserFilters,
    UserUpdateRequest,
    UserUpdateResponse,
    PasswordChangeRequest,
    BalanceRechargeRequest,
    PointsRechargeRequest,
)
from app.services.admin.admin_auth_service import AdminAuthService
from app.services.admin.admin_user_service import AdminUserManageService

logger = logging.getLogger(__name__)

router = APIRouter()


def get_user_order_schema(
    order_by: str = Query(
        "",
        description="排序字段，多个字段用逗号分隔，字段名前加-表示降序，如：-created_at,id。可用字段：id, username, email, is_active, created_at",
    )
) -> OrderSchema:
    """获取用户排序Schema"""
    return OrderSchema.with_allowed_fields(
        allowed_fields={"id", "username", "email", "is_active", "created_at"}, order_by=order_by
    )


@router.get("/list", tags=["用户管理"], response_model=Response[PaginationResult[UserDetailResponse]])
async def list_users(
    current_user: CurrentUser,
    filters: UserFilters = Depends(),
    order: OrderSchema = Depends(get_user_order_schema),
    pagination: PaginationParams = Depends(),
):
    """获取用户列表"""
    return Response.success(
        data=await AdminUserManageService.list(
            filters=filters,
            order=order,
            pagination=pagination,
        )
    )


@router.get("/detail", tags=["用户管理"], response_model=Response[UserDetailResponse])
async def get_user_detail(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
):
    """获取用户详情"""
    return Response.success(data=await AdminUserManageService.get_by_id(user_id))


@router.post("/create", tags=["用户管理"], response_model=Response[UserCreateResponse])
async def create_user(
    current_user: CurrentUser,
    user_in: UserCreateRequest = Body(..., description="用户创建信息"),
):
    """创建新用户"""
    return Response.success(data=await AdminUserManageService.create(user_in))


@router.post("/update", tags=["用户管理"], response_model=Response[UserUpdateResponse])
async def update_user(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
    user_in: UserUpdateRequest = Body(..., description="用户更新信息"),
):
    """更新用户"""
    return Response.success(data=await AdminUserManageService.update(user_id, user_in))


@router.post("/delete", tags=["用户管理"], response_model=Response[UserDeleteResponse])
async def delete_user(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
):
    """删除用户"""
    return Response.success(data=await AdminUserManageService.delete(user_id))


@router.post("/change-password", tags=["用户管理"], response_model=Response[UserDetailResponse])
async def change_password(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
    password_in: PasswordChangeRequest = Body(..., description="密码修改信息"),
):
    """修改用户密码"""
    return Response.success(data=await AdminUserManageService.change_password(user_id, password_in))


@router.post("/recharge-balance", tags=["账户充值"], response_model=Response[UserDetailResponse])
async def recharge_balance(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
    recharge_in: BalanceRechargeRequest = Body(..., description="余额充值信息"),
):
    """充值用户余额"""
    return Response.success(data=await AdminUserManageService.recharge_balance(user_id, recharge_in))


@router.post("/recharge-points", tags=["账户充值"], response_model=Response[UserDetailResponse])
async def recharge_points(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID"),
    recharge_in: PointsRechargeRequest = Body(..., description="积分充值信息"),
):
    """充值用户积分"""
    return Response.success(data=await AdminUserManageService.recharge_points(user_id, recharge_in))


@router.post("/kickout", tags=["会话管理"])
async def kickout_user(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID", title="用户ID"),
) -> Response:
    """踢出用户（使其所有设备登出）"""
    success = await AdminAuthService.kickout_user(user_id)
    if not success:
        return Response.error(message=t("error.auth.kickout_failed"))

    return Response.success(message=t("auth.kickout_success"))


@router.post("/force-logout", tags=["会话管理"])
async def force_logout(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID", title="用户ID"),
) -> Response:
    """强制用户登出"""
    success = await AdminAuthService.force_logout(user_id)
    if not success:
        return Response.error(message=t("error.auth.logout_failed"))

    return Response.success(message=t("auth.logout_success"))


@router.post("/disable-user", tags=["用户管理"])
async def disable_user(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID", title="用户ID"),
) -> Response:
    """禁用用户账号"""
    success = await AdminAuthService.disable_user(user_id)
    if not success:
        # 禁用失败
        return Response.error(message=t("error.auth.disable_failed"))
    return Response.success()


@router.post("/enable-user", tags=["用户管理"])
async def enable_user(
    current_user: CurrentUser,
    user_id: int = Query(..., description="用户ID", title="用户ID"),
) -> Response:
    """启用用户账号"""
    success = await AdminAuthService.enable_user(user_id)
    if not success:
        return Response.error(message=t("error.auth.enable_failed"))

    return Response.success()
